package com.example.flashsales.aspect;



import com.example.flashsales.entity.Result;
import com.example.flashsales.role.role;
import com.example.flashsales.service.impl.RoleServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * 权限切面
 */
@Aspect
@Component
public class RoleAspect {
    @Autowired
    RoleServiceImpl roleService;


//    /**
//     * 切入controller下面的所有方法
//     */
//    @Pointcut("execution(* com.gxh.demo.controller.*.*(..))")
//    private void pointcut(){
//
//    }


    /**
     * 根据注解切入
     */
    @Pointcut("@annotation(com.example.flashsales.role.role)")
    private void puOrder(){}


    @Around("puOrder()")
    public Result invoke(ProceedingJoinPoint joinPoint) throws Throwable{

        //获取切入的方法
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        //获取方法上的参数
        Object[] args = joinPoint.getArgs();
        //转换成 集合
        List<Object> list = Arrays.asList(args);
        //获取切入方法的注解role
        role r = method.getAnnotation(role.class);
        //注解里面的值
        final int role = r.role();
        //参数httpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) list.get(0);
        //用户id
        int id = Integer.parseInt(httpServletRequest.getAttribute("id")+"");
        final List<com.example.flashsales.entity.pojo.Method> methods = roleService.viewMethodByAdmin(id);
        boolean flag = false;
        for (com.example.flashsales.entity.pojo.Method method1 : methods) {
            if (method1.getId() == role){
                flag = true;
            }
        }
        if (flag){
            return (Result) joinPoint.proceed();
        }
        return Result.error("权限不够");
    }

}
